package pucp.carpooling;

import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.actionbarsherlock.app.SherlockFragment;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import pucp.carpooling.adapter.ListViewAdapterVehiculos;
import pucp.carpooling.controller.JSONParserObject;
import pucp.carpooling.model.UserLogeado;
import pucp.carpooling.R;

public class FragmentMisVehiculos extends SherlockFragment implements
		OnClickListener {
	public Button btnAgregar_Vehiculo;
	private static final String url = "http://subete.inf.pucp.edu.pe/ServiciosMobile/obtener_vehiculos_usuario";
	String[] polarizado, vehiculo, placa, asiento, combustible, color, year,
			idvehiculo;
	private static final String SUCCESS = "Success";
	private static final String TAG_VehiculosUsuario = "VehiculosUsuario";
	private static final String TAG_Marca = "Brand";
	private static final String TAG_Modelo = "Model";
	private static final String TAG_Placa = "Plate";
	private static final String TAG_Asientos = "Seats";
	private static final String TAG_Combustible = "FuelType";
	int[] fotoVehiculo;
	ListView list;
	ListViewAdapterVehiculos adapter;
	JSONParserObject jsonParser = new JSONParserObject();
	JSONArray vehiculos = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		onViewStateRestored(savedInstanceState);
		View view = inflater.inflate(R.layout.fragment_mis_vehiculos,
				container, false);
		list = (ListView) view.findViewById(R.id.listavehiculos);

		list.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				Intent i = new Intent(getActivity(),
						SingleItemViewVehiculos.class);

				i.putExtra("position", position);
				i.putExtra("idVehicle", idvehiculo);
				i.putExtra("vehiculo", vehiculo);
				i.putExtra("placa", placa);
				i.putExtra("asiento", asiento);
				i.putExtra("combustible", combustible);
				i.putExtra("flag", fotoVehiculo);
				i.putExtra("color", color);
				i.putExtra("polarizado", polarizado);
				i.putExtra("year", year);
				startActivity(i);

			}

		});

		btnAgregar_Vehiculo = (Button) view
				.findViewById(R.id.btnAgregarVehiculo);

		btnAgregar_Vehiculo.setOnClickListener(this);

		// set a listener to be invoked when the list reaches the end

		return view;

	}

	@Override
	public void onPause() {
		super.onPause();
		new getVehiculosUsuario().execute();

	}

	@Override
	public void onResume() {
		super.onResume();
		new getVehiculosUsuario().execute();

	}

	@Override
	public void onClick(View v) {
		Intent i = new Intent(getActivity(), RegistrarVehiculoActivity.class);
		switch (v.getId()) {
		case R.id.btnAgregarVehiculo:
			startActivity(i);
		default:
			break;
		}
	}

	private class getVehiculosUsuario extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			try {

				JSONParserObject sh = new JSONParserObject();
				List<NameValuePair> params = new ArrayList<NameValuePair>();
				final UserLogeado userlogged = (UserLogeado) getActivity()
						.getApplication();
				final String jsonLogin = userlogged.getJsonUser();
				JSONObject usuarioLogeado = new JSONObject(jsonLogin);
				params.add(new BasicNameValuePair("idUser", usuarioLogeado
						.getString("idUser")));

				String jsonStr = sh.makeServiceCall(url, JSONParserObject.POST,
						params);
				Log.d("Response: ", "> " + jsonStr);
				if (jsonStr != null) {
					try {
						JSONObject jsonObj = new JSONObject(jsonStr);
						if (jsonObj.getString(SUCCESS).equals("Yes")) {
							vehiculos = jsonObj
									.getJSONArray(TAG_VehiculosUsuario);

							vehiculo = new String[vehiculos.length()];
							idvehiculo = new String[vehiculos.length()];
							polarizado = new String[vehiculos.length()];
							placa = new String[vehiculos.length()];
							asiento = new String[vehiculos.length()];
							combustible = new String[vehiculos.length()];
							color = new String[vehiculos.length()];
							year = new String[vehiculos.length()];
							fotoVehiculo = new int[vehiculos.length()];

							for (int i = 0; i < vehiculos.length(); i++) {
								JSONObject c = vehiculos.getJSONObject(i);
								vehiculo[i] = c.getString(TAG_Marca) + " "
										+ c.getString(TAG_Modelo);
								placa[i] = c.getString(TAG_Placa);
								asiento[i] = c.getString(TAG_Asientos);
								combustible[i] = c.getString(TAG_Combustible);
								color[i] = c.getString("Color");
								idvehiculo[i] = c.getString("idVehicle");
								year[i] = c.getString("YearFactory");
								fotoVehiculo[i] = R.drawable.car;
								polarizado[i] = c.getString("TintedWindows");
							}
						} else {
							// no tiene vehiculos
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

			} catch (Exception e) {

			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			super.onPostExecute(result);

			if (vehiculo != null) {
				adapter = new ListViewAdapterVehiculos(getActivity(),
						idvehiculo, vehiculo, placa, asiento, combustible,
						fotoVehiculo);

				list.setAdapter(adapter);
			}

			super.onPostExecute(result);
		}

		@Override
		protected void onCancelled() {

		}
	}

}
